local LSM = LibStub("LibSharedMedia-3.0",true)
local activeTotems = {}
local elementsMap = {["Fire"] = 1, ["Earth"] = 2, ["Water"] = 3, ["Air"] = 4}

function Yata:InitTimer()
	self:RegisterEvent("PLAYER_DEAD")
	-- Watch for damage done to our totems
    self:RegisterEvent("PLAYER_TOTEM_UPDATE")
	self.DurationGroup = self:GetBarGroup("Totem Uptime") or self:NewBarGroup("Totem Uptime", nil, 150, 12)
	self.DurationGroup:SetFont(nil, 8)
	self.DurationGroup:SetColorAt(1.00, 0.0, 1.0, 0.0, 1)
	self.DurationGroup:SetColorAt(0.66, 1.0, 1.0, 0.0, 1)
	self.DurationGroup:SetColorAt(0.33, 1.0, 0.65, 0.0, 1)
	self.DurationGroup:SetColorAt(0.00, 1.0, 0.0, 0.0, 1)
	self.DurationGroup:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 200, 200)
	self.CooldownGroup = self:GetBarGroup("Totem Cooldown") or self:NewBarGroup("Totem Cooldown", nil, 150, 12)
	self.CooldownGroup:SetFont(nil, 8)
	self.CooldownGroup:SetColorAt(1.00, 1.0, 0.0, 0.0, 1)
	self.CooldownGroup:SetColorAt(0.66, 1.0, 0.65, 0.0, 1)
	self.CooldownGroup:SetColorAt(0.33, 1.0, 1.0, 0.0, 1)
	self.CooldownGroup:SetColorAt(0.00, 0.0, 1.0, 0.0, 1)
	self.CooldownGroup:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 300, 300)
	self:LoadTimerConfig()
end

function Yata:UpdateTimer(button)
	local seconds = GetTotemTimeLeft(elementsMap[button.Totem.Element])
	BuffFrame_UpdateDuration(button,seconds)
end

function Yata:SaveTimerConfig()
	local scale, x, y
	if not self.db.profile.DurationGroupPosition then 
		self.db.profile.DurationGroupPosition = {}
	end
	scale = self.DurationGroup:GetEffectiveScale()
	x = self.DurationGroup:GetLeft()/scale
	y = self.DurationGroup:GetBottom()/scale 
	self.db.profile.DurationGroupPosition.x = x
	self.db.profile.DurationGroupPosition.y = y
	
	if not self.db.profile.CooldownGroupPosition then 
		self.db.profile.CooldownGroupPosition = {}
	end
	scale = self.CooldownGroup:GetEffectiveScale()
	x = self.CooldownGroup:GetLeft()/scale
	y = self.CooldownGroup:GetBottom()/scale 
	self.db.profile.CooldownGroupPosition.x = x
	self.db.profile.CooldownGroupPosition.y = y	
end

function Yata:SetTimerScale(scale)
	self.DurationGroup:SetScale(scale)
	self.CooldownGroup:SetScale(scale)
end

function Yata:LoadTimerConfig()
	local scale, x, y
	if self.db.profile.DurationGroupPosition then 
		scale = self.DurationGroup:GetEffectiveScale()
		x = self.db.profile.DurationGroupPosition.x * scale
		y = self.db.profile.DurationGroupPosition.y * scale
		self.DurationGroup:ClearAllPoints()
		self.DurationGroup:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", x, y)
	end
	if self.db.profile.CooldownGroupPosition then 
		scale = self.CooldownGroup:GetEffectiveScale()
		x = self.db.profile.CooldownGroupPosition.x * scale
		y = self.db.profile.CooldownGroupPosition.y * scale
		self.CooldownGroup:ClearAllPoints()
		self.CooldownGroup:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", x, y)
	end
	if self.db.profile.Locked then
		self.DurationGroup:HideAnchor()
		self.CooldownGroup:HideAnchor()	
	end
	self.DurationGroup:SetScale(self.db.profile.TimerScale)
	self.DurationGroup:SetTexture(LSM:Fetch("statusbar", self.db.profile.TimerBarSkin))
	self.CooldownGroup:SetScale(self.db.profile.TimerScale)
	self.CooldownGroup:SetTexture(LSM:Fetch("statusbar", self.db.profile.TimerBarSkin))
end

function Yata:ShowTimerAnchors()
	self.DurationGroup:ShowAnchor()
	self.CooldownGroup:ShowAnchor()
end

function Yata:HideTimerAnchors()	
	self.DurationGroup:HideAnchor()
	self.CooldownGroup:HideAnchor()	
	self:SaveTimerConfig()
end

function Yata:PLAYER_DEAD()
	if self.db.profile.TimerEnabled then
		for k,b in pairs(activeTotems) do			
		    self:StopTimer(b)
		    activeTotems[k] = nil
		end
	end
end

function Yata:PLAYER_TOTEM_UPDATE(event, slot)
	local haveTotem, name, startTime, duration, icon = GetTotemInfo(slot)
	if self.db.profile.TimerEnabled then
		if haveTotem and string.len(name) > 0 then
			for k,b in pairs(self.TotemButtons.Buttons) do
				if  string.find(string.lower(name), string.lower(b.Totem.Name))  then
					if activeTotems[slot] then
						self:StopTimer(activeTotems[slot])
					end
					self:StartTimer(b,startTime, duration)
					activeTotems[slot] = b
					break
				end
			end
		else
			if activeTotems[slot] then
				self:StopTimer(activeTotems[slot])
				activeTotems[slot] = nil
			end
		end
	end
end


function Yata:StartTimer(button, startTime, duration)
	local totem = button.Totem
	if self.db.profile.TimerType == 1 then
		self.DurationGroup:NewTimerBar(totem.Element.."Duration", totem.Name, duration, duration, totem.Texture)
	elseif self.db.profile.TimerType == 2 then
		CooldownFrame_SetTimer(button.Cooldown, startTime, duration, 1)
		button:SetScript("OnUpdate", function() Yata:UpdateTimer(button) end)	
	end
end
function Yata:StopTimer(button)
	local totem = button.Totem
	if self.db.profile.TimerType == 1 then
		local bar = self.DurationGroup:GetBar(totem.Element.."Duration")
		self.DurationGroup:RemoveBar(bar)		
	elseif self.db.profile.TimerType == 2 then
		button:SetScript("OnUpdate", nil)		
		button.Duration:Hide()
	end	
	if totem.Cooldown > 0 then
		self:Cooldown(button)								
	elseif self.db.profile.TimerType == 2 then
		button.Cooldown:Hide()
	end
end
function Yata:Cooldown(button)
	local totem = button.Totem
    local start, duration, enabled = GetSpellCooldown(totem.SpellID,  BOOKTYPE_SPELL)
    local count = (start + duration - GetTime())
	if count > 0 then	
		if self.db.profile.TimerType == 1 then
			self.CooldownGroup:NewTimerBar(totem.Name.."Cooldown", totem.Name, count, count, totem.Texture)
		elseif self.db.profile.TimerType == 2 then
			CooldownFrame_SetTimer(button.Cooldown, start, duration, enabled)
			button:SetScript("OnUpdate", nil)
		end
	end
end